package com.daxia.bumall.web.controller.m;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.daxia.bumall.common.DecorateRequirementStatus;
import com.daxia.bumall.common.MyJSONObject;
import com.daxia.bumall.common.NeedLogin;
import com.daxia.bumall.common.OrderDesignerStatus;
import com.daxia.bumall.common.Sex;
import com.daxia.bumall.common.UserType;
import com.daxia.bumall.dto.CityDTO;
import com.daxia.bumall.dto.DesignerDTO;
import com.daxia.bumall.dto.OrderDesignerDTO;
import com.daxia.bumall.dto.UserDTO;
import com.daxia.bumall.exception.BizException;
import com.daxia.bumall.model.City;
import com.daxia.bumall.model.Designer;
import com.daxia.bumall.model.HouseStyle;
import com.daxia.bumall.model.HouseType;
import com.daxia.bumall.model.User;
import com.daxia.bumall.support.MPage;
import com.daxia.bumall.util.DateUtils;

@Controller
@RequestMapping(value = "/m/orderDesigner", produces = "application/json;charset=UTF-8")
public class MOrderDesignerController extends MBaseController {
	
	private static Logger logger = Logger.getLogger(MOrderDesignerController.class);
    
    @ResponseBody
    @RequestMapping("list")
    public String list(OrderDesignerDTO dto, MPage page) throws Exception {
    	MyJSONObject data = new MyJSONObject();
    	JSONArray orderDesignerInfos = new JSONArray();
    	dto.setStatus(OrderDesignerStatus.Init.getValue());
        List<OrderDesignerDTO> orderDesignerDTOs = orderDesignerService.find(dto, page);
        for (OrderDesignerDTO orderDesigner : orderDesignerDTOs) {
        	MyJSONObject od = new MyJSONObject();
        	od.put("id", orderDesigner.getId());
        	od.put("username", orderDesigner.getUser().getUsername());
        	od.put("nickName", orderDesigner.getUser().getNickName());
        	od.put("desc", getDesc(orderDesigner));
        	od.put("userHeadImage", orderDesigner.getUser().getHeadImage());
        	od.put("houseStyle", getHouseStyle(orderDesigner));
        	orderDesignerInfos.add(od);
        }
        data.put("orderDesignerInfos", orderDesignerInfos);
        data.put("total", orderDesignerService.countAllOfADay());
        data.put("succeed", orderDesignerService.countSuccedOfADay());
        return toJson(data);
    }
    
    @NeedLogin
    @ResponseBody
    @RequestMapping("myOrderDesigner")
    public String myOrderDesigner(MPage page) throws Exception {
    	MyJSONObject data = new MyJSONObject();
    	JSONArray orderDesignerInfos = new JSONArray();
    	
    	User user = getCurrentUser();
    
		OrderDesignerDTO orderDesignerQuery = new OrderDesignerDTO();
		if (user.getType().intValue() == UserType.Designer.getValue()) {
			Designer designer = new Designer();
    		User designerUser = new User();
    		designerUser.setId(user.getId());
    		designer.setUser(designerUser);
			orderDesignerQuery.setDesigner(designer);
		} else {
			User normalUser = new User();
    		normalUser.setId(user.getId());
			orderDesignerQuery.setUser(normalUser);
		}
		List<OrderDesignerDTO> orderDesignerDTOs = orderDesignerService.find(orderDesignerQuery , page);
        for (OrderDesignerDTO orderDesigner : orderDesignerDTOs) {
        	MyJSONObject od = new MyJSONObject();
        	od.put("id", orderDesigner.getId());
        	od.put("username", orderDesigner.getUser().getUsername());
        	od.put("nickName", orderDesigner.getUser().getNickName());
        	od.put("mobile", orderDesigner.getUser().getMobile());
        	od.put("desc", getDesc(orderDesigner));
        	od.put("userHeadImage", orderDesigner.getUser().getHeadImage());
        	od.put("houseStyle", getHouseStyle(orderDesigner));
        	od.put("status", orderDesigner.getStatus());
        	od.put("statusRemark", DecorateRequirementStatus.getByValue(orderDesigner.getStatus()).getRemark());
        	od.put("createTime", DateUtils.format(orderDesigner.getCreateTime(), "yyyy-MM-dd"));
        	if (orderDesigner.getDesigner() != null) {
        		MyJSONObject designerInfo = new MyJSONObject();
        		designerInfo.put("id", orderDesigner.getDesigner().getId());
        		designerInfo.put("mobile", orderDesigner.getDesigner().getUser().getMobile());
        		od.put("designerInfo", designerInfo);
        	}
        	orderDesignerInfos.add(od);
        }
        data.put("orderInfos", orderDesignerInfos);
        return toJson(data);
    }
    
    private Object getDesc(OrderDesignerDTO orderDesigner) {
    	String ret = "";
    	String area = orderDesigner.getArea();
    	HouseType houseType = orderDesigner.getHouseType();
    	if (houseType != null) {
    		ret += houseType.getName();
    	}
    	if (StringUtils.isNotBlank(area)) {
    		ret += "/" + area;
    	}
    	return ret;
	}

	private String getHouseStyle(OrderDesignerDTO orderDesigner) {
    	String ret = "";
    	HouseStyle houseStyle = orderDesigner.getHouseStyle();
    	if (houseStyle != null) {
    		ret += houseStyle.getName();
    	}
    	return ret;
	}

	/**
     * 预约设计师
     * @param cityId
     * @param communityName
     * @param area
     * @param houseStyleId
     * @param houseTypeId
     * @param orderDate
     * @return
     * @throws Exception
     */
    @NeedLogin
    @ResponseBody
	@RequestMapping("order")
	public String order(Long designerId, Long cityId, String cityName,  String communityName, String area, Long houseStyleId, Long houseTypeId, String orderDate, HttpServletRequest request) throws Exception {
    	logger.info("designerId : " + designerId);
    	
    	User user = getCurrentUser();
    	if (org.apache.commons.collections.CollectionUtils.isNotEmpty(user.getDesigners())) {
    		throw new BizException("设计师不能预约设计师.");
    	}
    	City city = new City();
    	if (cityId != null) {
    		CityDTO cityDTO = cityService.load(cityId);
    		BeanUtils.copyProperties(cityDTO, city);
    	} else if (StringUtils.isNotBlank(cityName)) {
    		CityDTO cityQuery = new CityDTO();
    		cityQuery.setName(cityName);
			CityDTO cityDTO = cityService.findOne(cityQuery );
    		BeanUtils.copyProperties(cityDTO, city);

    	}
    	String houseTypeImage = super.saveFilesAndReturnFileName(request);
    	notNull(designerId, "设计师不能为空");
    	OrderDesignerDTO o = new OrderDesignerDTO();
    	//notNull(cityId, "城市不能为空");
    	notNull(communityName, "小区名不能为空");
    	o.setCity(city);
    	o.setCommunityName(communityName);
    	o.setArea(area);
    	o.setHouseStyle(new HouseStyle());
    	o.getHouseStyle().setId(houseStyleId);
    	o.setHouseType(new HouseType());
    	o.getHouseType().setId(houseTypeId);
    	// 去掉预约日期
    	//SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    	//o.setOrderTime(dateFormat.parse(orderDate));
    	
    	o.setCreateTime(new Date());
    	o.setUser(new User());
    	o.getUser().setId(getCurrentUserDTO().getId());
    	o.setHouseTypeImage(houseTypeImage);
    	o.setStatus(OrderDesignerStatus.Init.getValue());
    	o.setDesigner(new Designer());
    	o.getDesigner().setId(designerId);
    	orderDesignerService.create(o);
		return toJson("");
	}
    
    
    @NeedLogin
    @ResponseBody
    @RequestMapping("rush")
    public String rush(Long id) throws Exception {
    	logger.info("ID IS : " + id);
    	notNull(id, "ID IS NULL.");
    	UserDTO currentUser = getCurrentUserDTO();
    	User user = new User();
    	BeanUtils.copyProperties(currentUser, user);
    	
    	DesignerDTO designDTOQuery = new DesignerDTO();
    	designDTOQuery.setUser(user);
		DesignerDTO designerDTO = designerService.findOne(designDTOQuery);
		
		if (designerDTO == null) {
			throw new BizException("此用户不是设计师用户");
		}
		
    	int i = orderDesignerService.updateDesigner(id, designerDTO.getId());
    	if (i <= 0) {
    		throw new BizException("抢单失败！");
    	} 
    	return toJson();
    }
    
    @ResponseBody
    @RequestMapping("detail")
    public String detail(Long id) throws Exception {
    	logger.info("ID is : " + id);
    	notNull(id, "id can not be null.");
    	MyJSONObject data = new MyJSONObject();
    	OrderDesignerDTO orderDesignerDTO = orderDesignerService.load(id);
    	MyJSONObject userInfo = new MyJSONObject();
    	userInfo.put("id", orderDesignerDTO.getUser().getId());
    	userInfo.put("headImage", orderDesignerDTO.getUser().getHeadImage());
    	userInfo.put("username", orderDesignerDTO.getUser().getUsername());
    	userInfo.put("nickName", orderDesignerDTO.getUser().getNickName());
    	userInfo.put("sex", orderDesignerDTO.getUser().getSex());
    	userInfo.put("sexRemark", Sex.getByValue(orderDesignerDTO.getUser().getSex()).getRemark());
    	String provinceName = "";
    	String cityName = "";
    	if (orderDesignerDTO.getUser().getProvince() != null) {
    		provinceName = orderDesignerDTO.getUser().getProvince().getName();
    	}
    	if (orderDesignerDTO.getUser().getCity() != null) {
    		provinceName = orderDesignerDTO.getUser().getCity().getName();
    	}
		userInfo.put("provinceName", provinceName);
		userInfo.put("cityName", cityName);
		userInfo.put("mobile", orderDesignerDTO.getUser().getMobile());
    	
		String houseTypeName = "";
		String houseStyleName = "";
		if (orderDesignerDTO.getHouseStyle() != null) {
			houseStyleName = orderDesignerDTO.getHouseStyle().getName();
		}
		if (orderDesignerDTO.getHouseType() != null) {
			houseTypeName = orderDesignerDTO.getHouseType().getName();
		}
    	data.put("city", cityName);
    	data.put("communityName", orderDesignerDTO.getCommunityName());
    	String area = "";
    	if (StringUtils.isNotBlank(orderDesignerDTO.getArea())) {
    		area += orderDesignerDTO.getArea() + "平米";
    	}
    	data.put("area", area);
    	data.put("houseTypeName", houseTypeName);
    	data.put("houseStyleName", houseStyleName);
    	data.put("houseImage", orderDesignerDTO.getHouseTypeImage());
    	data.put("status", orderDesignerDTO.getStatus());
    	data.put("statusRemark", OrderDesignerStatus.getByValue(orderDesignerDTO.getStatus()).getRemark());
    
    	data.put("userInfo", userInfo);
    	return toJson(data);
    }
    
    @Transactional
    @NeedLogin
    @ResponseBody
    @RequestMapping("handle")
    public String handle(Long id, Integer status) throws Exception {
    	
    	notNull(id, "orderdesigner can not be null.");
    	notNull(status, "status can not be null.");
    	User user = getCurrentUser();
     	
    	DesignerDTO designDTOQuery = new DesignerDTO();
    	User userQuery = new User();
    	userQuery.setId(user.getId());
    	designDTOQuery.setUser(userQuery);
		DesignerDTO designerDTO = designerService.findOne(designDTOQuery);
		Designer designer = new Designer();
		BeanUtils.copyProperties(designerDTO, designer);
		
		if (designerDTO == null) {
			throw new BizException("此用户不是设计师用户");
		}
		
		OrderDesignerDTO orderDesignerDTO = orderDesignerService.load(id);
		orderDesignerDTO.setStatus(status);
		orderDesignerDTO.setDesigner(designer);
		
		orderDesignerService.updateAllFields(orderDesignerDTO );
		
		designerDTO.setDealCount(designerDTO.getDealCount() + 1);
		designerService.updateAllFields(designerDTO);
		
    	
    	return toJson();
    }
}
